<?php 

Class wxmenuModel extends appModel
{
	/**
	 * 菜单排序
	 * @param $val
	 * @param $id
	 * @return
	 */
	public function ordering($val,$id)
	{
		$result = array('error' => 0, 'content' => '');
		$sql = "UPDATE ".$this->table('wxmenu')." SET ordering='$val' WHERE id='".$id."'";
		$res = $this->query($sql);
		if(!$res)
		{
			$result['error'] = 1;
			$result['content'] = '';
		}
		return $result;
	}
	
	/**
	 * 获取根目录菜单
	 * @return unknown
	 */
	public function get_parent_menu()
	{
		$sql = "SELECT id,name FROM ".$this->table('wxmenu')." WHERE parent_id=0";
		$res = $this->getAll($sql);
		return $res;
	}
	
	/**
	 * 获取子目录菜单
	 * @param unknown $pid
	 * @return unknown
	 */
	public function get_child_menu($pid)
	{
		$sql = "SELECT id,name FROM ".$this->table('wxmenu')." WHERE parent_id='".$pid."'";
		$res = $this->getAll($sql);
		return $res;
	}
	
	/**
	 * 获得菜单详情
	 * @param $id
	 * @return 
	 */
	public function get_wxmenu_info($id)
	{
		$sql = "SELECT parent_id,rule,name,id,url,type FROM ".$this->table('wxmenu')." WHERE id='".$id."'";
		$res = $this->getRow($sql);
		return $res;
	}
	
	/**
	 * 写入菜单
	 * @param $menu
	 * @return boolean
	 */
	public function insert_menu($menu)
	{
		foreach($menu as $k => $v)
		{
			$sub = $v['sub_button'];
			unset($v['sub_button']);
			$this->insert($v,'wxmenu');
			if($sub)
			{
				$pid = $this->insert_id();
				foreach($sub as $kk => $vv)
				{
					$sub_btn = $v['sub_button'];
					unset($vv['sub_button']);
					$vv['parent_id'] = $pid;
					$this->insert($vv,'wxmenu');
				}
			}
		}
		return true;
	}
	
	/**
	 * 获得微信菜单
	 * @param unknown $cfg
	 * @return string|unknown
	 */
	public function get_wxmenu($cfg = array())
	{
		if($cfg['is_show'] == 1)
		{
			$where ='is_show=1 AND';
		}
		$sql = "SELECT parent_id,name,id,ordering,url,rule,type,is_show FROM ".$this->table('wxmenu')." WHERE ".$where." parent_id=0";
		$res = $this->getAll($sql);
		
		$menu = array();
		$temp_list = '';
		
		if($res)
		{
			foreach($res as $k => $v)
			{
				if($cfg['parent_id'] === 0)
				{	
					$temp_list .= "<option value='".$v['id']."'>".$v['name']."</option>";
				}
				else 
				{
				  	$menu[$k] = $v;
				  	$sql = "SELECT parent_id,name,url,id,ordering,rule,type,is_show FROM ".$this->table('wxmenu')." WHERE ".$where." parent_id='".$v['id']."'";
				  	$menu[$k]['sub_button'] = $this->getAll($sql);
				}
			}
		}
		
		if($cfg['parent_id'] === 0)
		{
			return $temp_list;
		}
		else {
			return $menu;
		}
	}
	
}